﻿$(document).ready(function () {

    userId = readCookie("userId");
    if (userId == "") {
        window.location.href = 'login';
    }
    // Get Info User Login
    $.ajax({
        url: gb_servicePath + '/authenticateduser/ID/' + userId + '.json',
        crossDomain: "true",
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        traditional: true,
        data: "",
        dataType: 'json',
        success: function (data) {
            if (data.StatusCode == 200) {
                var admin = data.ReturnData;

                $('#lblUsername').html(admin.UserName);
                $('#lblFName').html(admin.FirstName);
                $('#lblLName').html(admin.LastName);
                $('#txtEmail').val(admin.EmailAddress);
                $('#txtPhone').val(admin.PhoneNumber);
                $('#ddlTimeZone option[name=' + admin.TimeZoneID + ']').attr("selected", "selected");
                $('#timezone_selection .customStyleSelectBoxInner').html($('#ddlTimeZone option[name=' + admin.TimeZoneID + ']').val());
                $('#lblEnterprise').html(admin.CompanyBrandInfo.CompanyInfo.Name);
                $('#lblBrandName').html(admin.CompanyBrandInfo.BrandInfo.Name);
                $('#lblBrandDescription').html(admin.CompanyBrandInfo.BrandInfo.Desc);

                $('#val_email').html(admin.EmailAddress);
                $('#val_phone').html(admin.PhoneNumber);
                $('#val_timezone').html($('#ddlTimeZone option:selected').val());

                $('.camp_content_main').remove();
                $.each(admin.CampaignRoleCountryInfo, function (i, val) {
                    var c = $(".camp_content_temp").clone();
                    $(c).removeClass("hide").removeClass('camp_content_temp').addClass('camp_content_main');
                    $(c).find(".td_campName").html(val.CampaignRoleInfo.CampaignInfo.Name);
                    $(c).find(".td_role").html(val.CampaignRoleInfo.RoleInfo.Name);
                    var countries = "";
                    $.each(val.CountryList, function (i, val_country) {
                        countries += val_country.Name + ", ";
                    });
                    $(c).find(".td_country").html(countries.substring(0, countries.length - 2));
                    $(".camp").append(c);
                });
            }
        },
        error: function (jqXHR, textStatus, xerror) {
            if (isBug) {
                alert("Error in /authenticateduser/ID/' + userId + '.json ->" + xerror);
            }
        }
    });
    //Get Details User by id

    // Get List Time Zone
    function getListTimeZone() {
        $.getJSON(gb_servicePath + '/countrypreference/list.json',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        $.each(json1.ReturnData, function (i, val) {
                            if (i == 0) {
                                var o = $("<option selected='selected' name='" + val.Timezone.Id + "' id='tz" + val.Timezone.Id + "' value='" + val.Timezone.Name + "' >" + val.Timezone.Name + "</option>");
                                $(".select_time").find(".customStyleSelectBoxInner").html(val.Timezone.Name);
                            } else {
                                var o = $("<option name='" + val.Timezone.Id + "' id='tz" + val.Timezone.Id + "' value='" + val.Timezone.Name + "' >" + val.Timezone.Name + "</option>");
                            }
                            if ($("#tz" + val.Timezone.Id).length == 0) {
                                $("#timezone_selection").find("select").append(o);
                            }
                        });
                    }
                });
    }

    $('.edit').css('display', 'none');
    $('.view').css('display', 'block');
    function checkMail() {
        var mail = $('#txtEmail').val();
        var emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (mail == '') {
            $('#title_mail').css('color', '#ff5050');
            $('#txtEmail').val('');
            $('#txtEmail').focus();
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            return false;
        }
        else if (emailReg.test(mail)) {
            // TODO: email is true
            $('#title_mail').css('color', '#595959');
            return true;
        }
        else {
            $('#title_mail').css('color', '#ff5050');
            $('#txtEmail').val('');
            $('#txtEmail').focus();
            $('#warning').html('Email address not on file');
            $('#warning').css('color', '#ff5050');
            return false;
        } //Please complete required fields
    }
    function checkEmty() {
        var co = true;
        var mail = $('#txtEmail').val();
        var phone = $('#txtPhone').val();
        var oldpass = $('#txtOldPassword').val();
        if (oldpass == '') {
            $('#title_pass').css('color', '#ff5050');
            $('#txtOldPassword').val('');
            $('#txtOldPassword').focus();
            $('#warning').html('Please enter your old password');
            $('#warning').css('color', '#ff5050');
            co = false;
        }
        if (phone == '') {
            $('#title_phone').css('color', '#ff5050');
            $('#txtPhone').val('');
            $('#txtPhone').focus();
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            co = false;
        }
        if (mail == '') {
            $('#title_mail').css('color', '#ff5050');
            $('#txtEmail').val('');
            $('#txtEmail').focus();
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            co = false;
        }
        return co;
    }

    //Edit Account to POST
    function EditAccount() {
        var authUser = new Object();
        authUser.email = $('#txtEmail').val();
        authUser.phonenumber = $('#txtPhone').val();
        authUser.timezone = $("#timezone_selection").find("option:selected").attr("name");
        authUser.userid = userId;
        $.ajax({
            url: gb_servicePath + "/authenticateduser/update/" + userId + ".json",
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: JSON.stringify(authUser),
            "dataType": 'json',
            success: function (data) {
                $('#val_email').html($('#txtEmail').val());
                $('#val_phone').html($('#txtPhone').val());
                $('#val_timezone').html($('#ddlTimeZone option:selected').val());
                $('.edit').css('display', 'none');
                $('.view').css('display', 'block');
                if (getURLback('ref') != '' && getURLback('ref') != '-' && getURLback('ref') != 'null') {
                    window.location.href = '../' + getURLback('ref');
                }
                else {
                    window.location.href = '../';
                }
            },
            error: function (jqXHR, textStatus) {
                alert("Error");
                alert(authUser);
            }

        });
    }
    //Build Reset Pass to POST
    function buildResetPass() {
        var Reset = new Object();
        Reset.username = $('#lblUsername').html();
        Reset.password = $('#txtOldPassword').val();
        Reset.newpassword = $('#txtNewPass').val();

        return Reset;
    }

    $('#btnEdit').click(function () {
        $('.edit').css('display', 'block');
        $('.view').css('display', 'none');
        $('#btn_Cancel').click(function () {
            if (getURLback('ref') != '' && getURLback('ref') != '-' && getURLback('ref') != 'null') {
                window.location.href = '../' + getURLback('ref');
            }
            else {
                window.location.href = '../';
            }
        });
        $('#btn_Save').click(function () {
            var newpass = $('#txtNewPass').val();
            var repass = $('#txtRePass').val();
            $('#title_newpass').css('color', '#595959'); $('#title_repass').css('color', '#595959');
            if (!checkEmty()) {
                return false;
            } else {
                if (!checkMail()) {
                    return false;
                }
                if (newpass.length > 0 || repass.length > 0) {
                    if (newpass.length < 6 && newpass != '') {
                        $('#title_newpass').css('color', '#ff5050');
                        $('#title_repass').css('color', '#ff5050');
                        $('#txtNewPass').focus();
                        $('#warning').html('Password fields do not match');
                        $('#warning').css('color', '#ff5050');
                        return false;
                    }
                    else {
                        if (repass != newpass) {
                            $('#title_newpass').css('color', '#ff5050');
                            $('#title_repass').css('color', '#ff5050');
                            $('#txtRePass').focus();
                            //$('#warning').html('Confirmation Password is incorrect');
                            $('#warning').html('Password fields do not match');
                            $('#warning').css('color', '#ff5050');
                            return false;
                        }
                        else {
                            var Reset = buildResetPass();
                            $.ajax({
                                url: gb_servicePath + "authenticateduser/resetpassword.json",
                                crossDomain: "true",
                                type: "POST",
                                contentType: 'application/json; charset=utf-8',
                                traditional: true,
                                data: JSON.stringify(Reset),
                                "dataType": 'json',
                                success: function (data) {
                                    EditAccount();
                                },
                                error: function (jqXHR, textStatus) {
                                    if (isBug) {
                                        alert("Error");
                                        alert(Reset);
                                    }
                                }

                            });
                        }
                    }
                }
                else {
                    EditAccount();
                }
            }


        });
        $('select.select_long').customStyle();
    });
    getListTimeZone();
});
